/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.dao.MapFenceRepository;
import cc.iotkit.data.manager.IMapFenceData;
import cc.iotkit.data.model.QTbSysDictData;
import cc.iotkit.data.model.TbDeviceGroup;
import cc.iotkit.data.model.TbMapFence;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.device.DeviceGroup;
import cc.iotkit.model.map.MapFence;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;

import static cc.iotkit.data.model.QTbMapFence.tbMapFence;

@Primary
@Service
public class MapFenceDataImpl implements IMapFenceData, IJPACommData<MapFence, Long> {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private MapFenceRepository MapFenceRepository;

    @Override
    public JpaRepository getBaseRepository() {
        return MapFenceRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbMapFence.class;
    }

    @Override
    public Class getTClass() {
        return MapFence.class;
    }



    @Override
    public MapFence findById(Long s) {
        return MapstructUtils.convert(MapFenceRepository.findById(s).orElse(null), MapFence.class);
    }

    @Override
    public MapFence save(MapFence data) {
        if (data.getId()==null||data.getId().equals(0L)) {
            data.setTenantId(Long.valueOf(LoginHelper.getTenantId()));
            data.setUid(LoginHelper.getUserId());
            data.setCreateAt(System.currentTimeMillis());
            data.setCreateBy(LoginHelper.getUserId());
            data.setCreateDept(LoginHelper.getDeptId());
        }else{
            data.setUpdateAt(System.currentTimeMillis());
            data.setUpdateBy(LoginHelper.getUserId());
        }
        TbMapFence result=MapFenceRepository.save(MapstructUtils.convert(data, TbMapFence.class));
        return MapstructUtils.convert(result,MapFence.class);
    }


    @Override
    public List<MapFence> findAll() {
        return MapstructUtils.convert(MapFenceRepository.findAll(), MapFence.class);
    }
    private Predicate buildPredicate(MapFence data) {
        return PredicateBuilder.instance()
                .and(data.getId()!=null, () -> tbMapFence.id.eq(data.getId()))
                .build();
    }

    public JPAQuery<MapFence> buildSelect(MapFence data){
        Predicate predicate = buildPredicate(data);
        //关联多个相同表需要定义不同的别名
        QTbSysDictData tbSysDictDataStatus=new  QTbSysDictData("tbSysDictDataStatus");
        return jpaQueryFactory.select(Projections.bean(MapFence.class,
                        tbMapFence.id,tbMapFence.remark,tbMapFence.uid,tbMapFence.createAt,tbMapFence.createDept,
                        tbMapFence.fenceName,tbMapFence.fenceDesc,tbMapFence.fenceType,tbMapFence.center,
                        tbMapFence.radius,tbMapFence.points,tbMapFence.bufferradius,tbMapFence.adcode,
                        tbMapFence.tenantId,tbMapFence.updateAt,tbMapFence.updateBy,tbMapFence.gfid,
                        Expressions.as(tbSysDictDataStatus.dictLabel, Expressions.stringPath("fenceTypeName"))
                ))
                .from(tbMapFence)
                .leftJoin(tbSysDictDataStatus).on(tbSysDictDataStatus.dictType.eq("map_fence_type").and(tbSysDictDataStatus.dictValue.eq(tbMapFence.fenceType)))
                .where(predicate);
    }

    public List<MapFence> findAllByCondition(MapFence query) {
        List<MapFence> results = buildSelect(query).fetch();
        return results;

    }

    public Paging<MapFence> findAllByConditions(PageRequest<MapFence> pageRequest) {
        MapFence data = pageRequest.getData();
        QueryResults<MapFence> results = buildSelect(data).limit(pageRequest.getPageSize()).offset(pageRequest.getOffset()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());

    }
}
